package com.zjxny.jobs;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.zjxny.exception.TrafficException;
import com.zjxny.model.CarInfo;
import com.zjxny.service.TrafficService;
import com.zjxny.service.WxCpZjService;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.erupt.core.annotation.EruptHandlerNaming;
import xyz.erupt.job.config.EruptJobProp;
import xyz.erupt.job.handler.EruptJobHandler;
import xyz.erupt.job.service.EruptJobService;
import xyz.erupt.jpa.dao.EruptDao;

@Service
@Slf4j
@EruptHandlerNaming("获取违章数据") 
public class TrafficJob implements EruptJobHandler{
	
	private final Lock lock = new ReentrantLock();
    private boolean shouldSkip = false;
	
	@Resource
	private EruptDao eruptDao;

	@Resource
	private EruptJobService eruptJobService;

	@Resource
	private EruptJobProp eruptJobProp;

	@Resource
	private JdbcTemplate jdbcTemplate;
	
	@Resource
	TrafficService trafficService;
	
	@Resource
	WxCpZjService wxCpZjService;
	
	@Value("${traffic.sleep:1000}")
	Long sleepTime;
	
	@Value("${traffic.battch.limit:10}")
	Integer limit;
	
	@Override
	public String exec(String code, String param) {
		log.info("TrafficJob.exec ...");
		
		lock.lock();
		try {
			if (shouldSkip) {
				log.info("Skipping task...");
				return null;
			}

			shouldSkip = true;
			
			//获取所有含有违章未处理的车辆 用此车辆信息获取违章信息
			String sql = "select t1.id from car_info t1 left join account_info t2 on t2.id=t1.account_info_id where t1.task_status=1 and t1.zt like '%G%' and t2.is_valid=1";
			if(StrUtil.isNotBlank(param)) {
				sql = "select t1.id from car_info t1 left join account_info t2 on t2.id=t1.account_info_id where t1.task_status=1 and t2.is_valid=1";
			}
//			sql+=" and t1.id=775";
			sql +=" limit 0,"+limit;
			
			List<Long> carIds = jdbcTemplate.queryForList(sql, Long.class);
			
			log.info("TrafficJob.exec car.num={}",null!=carIds?carIds.size():0);
			try {
				Iterator<Long> iter = carIds.iterator();
				while(iter.hasNext()) {
					Long carId = iter.next();
					if(sleepTime>0) {
						try {
							Thread.sleep(sleepTime);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					CarInfo carInfo = eruptDao.queryEntity(CarInfo.class,"id="+carId);
					if(!carInfo.getAccountInfo().getIsValid()) {
						log.warn("{} token is expire",carInfo.getAccountInfo().getSimpleTitle());
						continue;
					}
					
					log.info("gettrafficdata hphm={}",carInfo.getHphm());
					//营运车
					if(carInfo.getIsOperation()){
						trafficService.getOperationTrafficList(carInfo);
					} else if(carInfo.getIsBiz()) {//租赁业务车辆
						trafficService.getBizTrafficList(carInfo);
					} else {//非营运车辆
						trafficService.getTrafficList(carInfo);
					}
					
					//执行完后记得更新任务状态为0
					jdbcTemplate.update("update car_info set task_status=0 where id="+carId);
				}
			} catch (TrafficException e) {
				log.warn("TrafficJob.session.expire, toUser={}, account={}",e.getToUser(),e.getAccountName());

				//获取所属公司 及 通知用户信息
				if(StrUtil.isNotBlank(e.getToUser())) {				
					wxCpZjService.sendNotifyMessage(e.getToUser(),String.format("%s会话过期,请及时处理!", e.getAccountName()));
				}
			}
			shouldSkip = false;
		} finally {
			shouldSkip = false;
			lock.unlock();
		}
		return null;
	}
}